﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Runtime.Serialization;

namespace SSFT
{
	public static class Util
	{
		public static string BytesToString(float num_bytes)
		{
			float result = num_bytes;

			if (result < 1000)
				return string.Format("{0:0.0} bytes", result);
			if ((result /= 1000) < 1000)
				return string.Format("{0:0.0} kB", result);
			if ((result /= 1000) < 1000)
				return string.Format("{0:0.0} MB", result);
			result /= 1000;
			return string.Format("{0:0.0} GB", result);
		}

		public static string ExceptionToString(Exception ex)
		{
			while (ex.InnerException != null)
				ex = ex.InnerException;

			if (ex is SocketException)
				switch ((ex as SocketException).SocketErrorCode)
				{
					case SocketError.AddressAlreadyInUse:
						return "Address already in use";
					case SocketError.ConnectionRefused:
						return "Connection refused";
					case SocketError.ConnectionReset:
					case SocketError.ConnectionAborted:
						return "Connection reset by peer";
					case SocketError.HostNotFound:
						return "Unknown host";
					case SocketError.NetworkDown:
						return "Network down";
					case SocketError.HostUnreachable:
					case SocketError.NetworkUnreachable:
						return "No route to host";
					case SocketError.TimedOut:
						return "Host timed out";
					default:
						return ex.Message;
				}
			if (ex is ArgumentException)
				return "Invalid hostname or port number";
			if (ex is SerializationException)
				return "Failed to communicate with host";
			if (ex is IOException)
				return ex.Message;
			return ex.Message;
		}

		public static IPAddress GetIP4Local()
		{
			foreach (NetworkInterface iface in NetworkInterface.GetAllNetworkInterfaces())
			{
				IPInterfaceProperties ipprops = iface.GetIPProperties();
				UnicastIPAddressInformationCollection uniCast = ipprops.UnicastAddresses;
				foreach (UnicastIPAddressInformation uni in uniCast)
				{
					if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
						return uni.Address;
				}
			}
			return null;
		}

		public static void SSFTError(string msg)
		{
			MessageBox.Show(msg, "SSFT", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		public static void SSFTWarning(string msg)
		{
			MessageBox.Show(msg, "SSFT", MessageBoxButtons.OK, MessageBoxIcon.Warning);
		}

		public static void SSFTInfo(string msg)
		{
			MessageBox.Show(msg, "SSFT", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}
	}
}